package mysql

import (
	"videos/videorpc/videorpc"

	"gorm.io/gorm"
)

// 视频

type Video struct {
	gorm.Model
	UserId  int    `gorm:"type:int;not null;comment:用户ID"`
	Title   string `gorm:"type:varchar(30);not null;comment:视频标题"`
	Style   string `gorm:"type:varchar(30);not null;comment:视频分类"`
	TopicId int    `gorm:"type:int;not null;comment:话题ID"`
}

// 视频用户话题

type VideoUserTopic struct {
	VideoId  int
	Title    string
	Style    string
	NickName string
}

// 视频用户详情

func (u *VideoUserTopic) VideoDetail(db *gorm.DB, id int64) error {
	/*
		select
		videos.id as VideoId,
		videos.title as title,
		videos.style as style,
		users.nick_name as nick_name
		from videos
		left join users on users.id = videos.user_id
	*/
	return db.Model(&Video{}).
		Select(
			"videos.id as VideoId",
			"videos.title as title",
			"videos.style as style",
			"users.nick_name as nick_name",
		).
		Joins("left join users on users.id = videos.user_id").
		Debug().Where("videos.id = ?", id).Find(u).Error
}

// 视频发布

func (v *Video) VideoAdd(db *gorm.DB) error {
	return db.Debug().Create(v).Error
}

// 修改视频

func (v *Video) VideoUpdate(db *gorm.DB) error {
	return db.Debug().Updates(v).Error
}

// 删除视频

func (v *Video) VideoDel(db *gorm.DB, id int64) error {
	return db.Debug().Where("id=?", id).Delete(v).Error
}

// 视频列表

func VideoList(db *gorm.DB, in *videorpc.VideoListRequest) []*videorpc.VideoList {
	/*
		select
		videos.id as VideoId,
		videos.title as title,
		videos.style as style,
		users.nick_name as nick_name,
		users.head_image as head_image
		from videos
		left join users on users.id = videos.user_id
	*/
	var list []*videorpc.VideoList

	tx := db.Model(&Video{}).
		Select(
			"videos.id as VideoId",
			"videos.title as title",
			"videos.style as style",
			"videos.created_at",
			"users.nick_name as nick_name",
			"users.head_image as head_image",
		).
		Joins("left join users on users.id = videos.user_id").
		Debug().Scopes(Paginate(int(in.Page), int(in.Size))).Order("videos.created_at desc")

	if in.NickName == "" {
		tx = tx.Where("nickName like ?", "%"+in.NickName+"%")
	}

	tx.Find(&list)

	return list
}
